// utils/storage.js

/**
 * 本地存储工具类
 * 提供统一的数据存储接口，支持过期时间设置
 */

class Storage {
  /**
   * 设置存储数据
   * @param {string} key 存储键
   * @param {*} value 存储值
   * @param {number} expireTime 过期时间(分钟)，0表示永不过期
   */
  set(key, value, expireTime = 0) {
    try {
      const data = {
        value,
        createTime: Date.now(),
        expireTime: expireTime > 0 ? Date.now() + expireTime * 60 * 1000 : 0
      }
      wx.setStorageSync(key, data)
      return true
    } catch (error) {
      console.error('Storage set error:', error)
      return false
    }
  }

  /**
   * 获取存储数据
   * @param {string} key 存储键
   * @param {*} defaultValue 默认值
   */
  get(key, defaultValue = null) {
    try {
      const data = wx.getStorageSync(key)
      
      if (!data) {
        return defaultValue
      }

      // 检查是否过期
      if (data.expireTime && Date.now() > data.expireTime) {
        this.remove(key)
        return defaultValue
      }

      return data.value
    } catch (error) {
      console.error('Storage get error:', error)
      return defaultValue
    }
  }

  /**
   * 删除存储数据
   * @param {string} key 存储键
   */
  remove(key) {
    try {
      wx.removeStorageSync(key)
      return true
    } catch (error) {
      console.error('Storage remove error:', error)
      return false
    }
  }

  /**
   * 清除所有存储数据
   */
  clear() {
    try {
      wx.clearStorageSync()
      return true
    } catch (error) {
      console.error('Storage clear error:', error)
      return false
    }
  }

  /**
   * 获取存储信息
   */
  getInfo() {
    try {
      return wx.getStorageInfoSync()
    } catch (error) {
      console.error('Storage getInfo error:', error)
      return null
    }
  }

  /**
   * 检查存储键是否存在
   * @param {string} key 存储键
   */
  has(key) {
    try {
      const data = wx.getStorageSync(key)
      if (!data) return false
      
      // 检查是否过期
      if (data.expireTime && Date.now() > data.expireTime) {
        this.remove(key)
        return false
      }
      
      return true
    } catch (error) {
      console.error('Storage has error:', error)
      return false
    }
  }

  /**
   * 获取所有存储键
   */
  keys() {
    try {
      const info = wx.getStorageInfoSync()
      return info.keys || []
    } catch (error) {
      console.error('Storage keys error:', error)
      return []
    }
  }

  /**
   * 清理过期数据
   */
  cleanExpired() {
    try {
      const keys = this.keys()
      let cleanedCount = 0
      
      keys.forEach(key => {
        const data = wx.getStorageSync(key)
        if (data && data.expireTime && Date.now() > data.expireTime) {
          this.remove(key)
          cleanedCount++
        }
      })
      
      console.log(`清理了 ${cleanedCount} 个过期数据`)
      return cleanedCount
    } catch (error) {
      console.error('Storage cleanExpired error:', error)
      return 0
    }
  }
}

// 创建存储实例
const storage = new Storage()

// 预定义的存储键
export const STORAGE_KEYS = {
  USER_INFO: 'userInfo',
  USER_TOKEN: 'token',
  CART_DATA: 'cartData',
  SEARCH_HISTORY: 'searchHistory',
  ADDRESS_LIST: 'addressList',
  SETTINGS: 'settings',
  PRODUCT_CACHE: 'productCache',
  ORDER_CACHE: 'orderCache'
}

// 便捷方法
export const storageUtils = {
  // 用户信息
  setUserInfo(userInfo) {
    return storage.set(STORAGE_KEYS.USER_INFO, userInfo, 30 * 24 * 60) // 30天
  },
  
  getUserInfo() {
    return storage.get(STORAGE_KEYS.USER_INFO, null)
  },

  // 用户令牌
  setToken(token) {
    return storage.set(STORAGE_KEYS.USER_TOKEN, token, 7 * 24 * 60) // 7天
  },
  
  getToken() {
    return storage.get(STORAGE_KEYS.USER_TOKEN, '')
  },

  // 购物车数据
  setCartData(cartData) {
    return storage.set(STORAGE_KEYS.CART_DATA, cartData, 24 * 60) // 1天
  },
  
  getCartData() {
    return storage.get(STORAGE_KEYS.CART_DATA, [])
  },

  // 搜索历史
  setSearchHistory(history) {
    return storage.set(STORAGE_KEYS.SEARCH_HISTORY, history, 7 * 24 * 60) // 7天
  },
  
  getSearchHistory() {
    return storage.get(STORAGE_KEYS.SEARCH_HISTORY, [])
  },

  // 地址列表
  setAddressList(addresses) {
    return storage.set(STORAGE_KEYS.ADDRESS_LIST, addresses, 30 * 24 * 60) // 30天
  },
  
  getAddressList() {
    return storage.get(STORAGE_KEYS.ADDRESS_LIST, [])
  },

  // 应用设置
  setSettings(settings) {
    return storage.set(STORAGE_KEYS.SETTINGS, settings, 0) // 永不过期
  },
  
  getSettings() {
    return storage.get(STORAGE_KEYS.SETTINGS, {})
  },

  // 清理缓存
  clearCache() {
    storage.remove(STORAGE_KEYS.PRODUCT_CACHE)
    storage.remove(STORAGE_KEYS.ORDER_CACHE)
  },

  // 清理所有数据
  clearAll() {
    storage.clear()
  }
}

export default storage 